// controllers/bookController.js
const db = require('../config/db');
const fs = require('fs');
const path = require('path');
exports.getBooks = (req, res) => {
    db.query('SELECT * FROM os_books', (err, results) => {
        if (err) {
            res.status(500).json({ error: '从数据库获取数据时出错' });
            return;
        }
        res.json(results);
    });
};

exports.searchBook = (req, res) => {
    const keyword = req.query.keyword;
    const query = `SELECT * FROM os_books WHERE title LIKE ? OR id LIKE ? OR author LIKE ? OR press LIKE ?`;
    const searchKeyword = `%${keyword}%`;
    if (req.query.keyword === '') {
        res.status(400).json({ message: '请输入搜索关键字' });
    } else {
        db.query(query, [searchKeyword,searchKeyword,searchKeyword,searchKeyword], (error, results) => {
            if (error) {
                res.status(500).json({ error: 'Error' });
                return;
            }
            res.json(results);
        });
    }
};

exports.addBook = (req, res) => {
    const { image,title,author,press,about,price } = req.body;
    const sqlInsert = 'INSERT INTO os_books (image,title,author,press,about,price) VALUES (?, ?, ?, ?, ?, ?)';
    db.query(sqlInsert, [image,title,author,press,about,price], (err, results) => {
        if (err) {
            res.status(500).json({message:'插入数据库失败'});
            return;
        }
        if (results.affectedRows > 0) {
            res.status(200).json({ message: '添加成功' });
        } else {
            res.status(400).json({ message: '添加失败' });
        }
    });
};

exports.deleteBook = (req, res) => {
    const { id } = req.params;
    const sqlSelect = 'SELECT image FROM os_books WHERE id = ?';
    db.query(sqlSelect, [id], (err, results) => {
        if (err) {
            res.status(500).send('查询数据库失败');
            return;
        }
        if (results.length === 0) {
            res.status(404).json({ message: '未找到数据', id: id });
            return;
        }
        const filename = results[0].image;
        if (filename === '') {
            const sqlDelete = 'DELETE FROM os_books WHERE id = ?';
            db.query(sqlDelete, [id], (err, results) => {
                if (err) {
                    res.status(500).json({ message: '删除数据库失败' });
                    return;
                }
                if (results.affectedRows > 0) {
                    res.status(200).json({ message: '删除成功' });
                } else {
                    res.status(404).json({ message: '未找到数据', id: id });
                }
            });
            return;
        }
        const parsedUrl = new URL(filename);
        const pathname = parsedUrl.pathname;
        const filePath = path.join(__dirname, '..', 'uploads', path.basename(pathname));
        const sqlDelete = 'DELETE FROM os_books WHERE id = ?';
        db.query(sqlDelete, [id], (err, results) => {
            if (err) {
                res.status(500).json({ message: '删除数据库失败' });
                return;
            }
            if (results.affectedRows > 0) {
                fs.unlink(filePath, (err) => {
                    res.status(200).json({ message: '删除成功' });
                });
            } else {
                res.status(404).json({ message: '未找到数据', id: id });
            }
        });
    });
};

exports.updateBook = (req, res) => {
    const { id } = req.params;
    const { image,title,author,press,about,price } = req.body;
    const sql = 'UPDATE os_books SET image = ?, title = ?, author = ?, press = ?, about = ? ,price = ? WHERE id = ?';
    db.query(sql, [image,title,author,press,about,price,id], (err, results) => {
        if (err) {
            res.status(500).send('插入数据库失败');
            return;
        }
        if (results.affectedRows > 0) {
            res.status(200).json({ message: '修改成功',image });
        } else {
            res.status(400).json({ message: '修改失败' });
        }
    });
};

exports.bookNum = (req, res) => {
    db.query('SELECT COUNT(*) AS total FROM os_books', (err, results) => {
        if (err) {
            res.status(500).json({ message: '查询数据库失败' });
            return;
        }
        const total = results[0].total;
        res.json({ total });
    });
};

exports.upLoad = (req, res) => {
    if (req.file) {
        // 构建图片URL
        const imageUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`;
        res.json({ imageUrl });
    } else {
        res.status(400).json({ error: '请选择一个文件上传' });
    }
};

exports.deleteImage = (req, res) => {
    const { imageUrl } = req.body;
    const imageFilePath = path.join(__dirname, '..', 'uploads', path.basename(imageUrl));
    fs.unlink(imageFilePath, (err) => {
        if (err) {
            console.log(err)
            return res.status(500).json({ message: "删除图片失败" });
        }
        res.json({ message: "删除图片成功" });
    });
};
